package main

import (
	"context"
	"flag"
	"gRPC_Server/helper"
	"gRPC_Server/pbfiles"
	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
)

const (
	endPointAddr = "127.0.0.1:8888"
	httpAddress  = "127.0.0.1:8080"
)

func main() {
	gwmux := runtime.NewServeMux() //创建路由
	dialOptions := []grpc.DialOption{}
	enableTLS := flag.Bool("tls", true, "enable SSL/TLS")
	if *enableTLS {
		tlsCreDentials, err := helper.GetClientCreds()
		if err != nil {
			log.Fatal("cannot load TLS credentials: %w", err)
		}
		dialOptions = append(dialOptions, grpc.WithTransportCredentials(tlsCreDentials))
	} else {
		dialOptions = append(dialOptions, grpc.WithTransportCredentials(insecure.NewCredentials()))
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	err := pbfiles.RegisterAuthServiceHandlerFromEndpoint(ctx, gwmux, endPointAddr, dialOptions) // 将http请求转为grpc请求
	if err != nil {
		log.Fatal(err)
	}

	err = pbfiles.RegisterLaptopServiceHandlerFromEndpoint(ctx, gwmux, endPointAddr, dialOptions)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Start REST server at %s, TLS = %t", httpAddress, *enableTLS)
	httpServer := &http.Server{
		Addr:    httpAddress, //暴露给http服务的端口地址
		Handler: gwmux,
	}
	err = httpServer.ListenAndServe()
	if err != nil {
		log.Fatal("cannot start server: ", err)
	}
}
